package com.gitee.l0km.jsonvisitor.fastjson;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * Helper class that wraps a byte[] so that it can expand and be reused. Users
 * should call resizeIfNecessary to make sure the buffer has suitable capacity,
 * and then use the array as needed. Note that the internal array will grow at a
 * rate slightly faster than the requested capacity with the (untested)
 * objective of avoiding expensive buffer allocations and copies.
 */
class AutoExpandingBuffer {
	private byte[] array;
	private int pos;

	private final double growthCoefficient;

	public AutoExpandingBuffer(int initialCapacity, double growthCoefficient) {
		if (growthCoefficient < 1.0) {
			throw new IllegalArgumentException("Growth coefficient must be >= 1.0");
		}
		array = new byte[initialCapacity];
		this.growthCoefficient = growthCoefficient;
		this.pos = 0;
	}
	public AutoExpandingBuffer() {
		this(256, 2);
	}
	private void resizeIfNecessary(int size) {
		if (array.length < size) {
			byte[] newBuf = new byte[(int) (size * growthCoefficient)];
			System.arraycopy(array, 0, newBuf, 0, array.length);
			array = newBuf;
		}
	}

	public void write(byte[] toWrite, int off, int len) {
		resizeIfNecessary(pos + len);
		System.arraycopy(toWrite, off, array, pos, len);
		pos += len;
	}

	public void write(byte[] toWrite) {
		write(toWrite, 0, toWrite.length);
	}
	public void write(ByteBuffer buffer) {
		if(null != buffer){
			byte[] bytes = new byte[buffer.remaining()];
			buffer.get(bytes);
			write(bytes);
		}
	}

	public byte[] array() {
		return array;
	}

	public int pos() {
		return pos;
	}

	public void reset() {
		pos = 0;
	}

	public byte[] copy() {
		return Arrays.copyOf(array,pos);
	}
}